﻿/**
* CRL
*/
using CRL;
using CRL.LambdaQuery;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CRL.Elasticsearch.ESEx
{
    public sealed partial class ESExtend
    {
        int Update2<TModel>(BoolQuery filter, ParameCollection setValue)
        {
            var client = getClient();
            var templateArry = setValue.Select(b => $"ctx._source.{b.Key}=params.{b.Key}");
            var template = string.Join(";", templateArry);
            var script2 = new InlineScript(template)
            {
                Params = setValue
            };
            var result = client.UpdateByQuery(new UpdateByQueryRequest(IndexName) { Query = filter, Script = script2 });
            return (int)result.Updated;
        }
        public override int Update<TModel>(ILambdaQuery<TModel> iQuery, ParameCollection setValue)
        {
            var query1 = iQuery as ESLambdaQuery<TModel>;
            if (query1.__GroupFields != null)
            {
                throw new Exception("update不支持group查询");
            }
            if (query1.__Relations != null && query1.__Relations.Count > 1)
            {
                throw new Exception("update关联不支持多次");
            }
            if (setValue.Count == 0)
            {
                throw new ArgumentNullException("更新时发生错误,参数值为空 ParameCollection setValue");
            }
            var query = query1 as ESLambdaQuery<TModel>;
            var bq = new BoolQuery() { Filter = query.queryContainers };
            return Update2<TModel>(bq, setValue);
        }
        public override int Update<TModel>(List<TModel> objs)
        {
            throw new NotImplementedException();
        }

    }
}
